const svgCaptcha = require('svg-captcha')
const serviceModel = require('../model/serviceModel')
const teamModel = require('../model/teamModel')
const bannerModel = require('../model/bannerModel')

const pagesControl = {}

pagesControl.checkCode = (req, res) => {
  const cap = svgCaptcha.create({
    size: 4,
    ignoreChars: 'iI10oOLlbB8',
    noise: 1
  })

  req.session.captcha = cap.text
  res.type('svg')
  res.status(200).send(cap.data)
}

pagesControl.feedBack = async (req, res) => {
  console.log(req.session.captcha)
  if (req.session.captcha && req.body.checkcode) {
    if (req.session.captcha.toLowerCase() == req.body.checkcode.toLowerCase()) {
      const service = {
        name: req.body.name,
        contact: req.body.contact,
        address: req.body.address,
        yixiang: req.body.yixiang,
        problem: req.body.problem,
        ip: req.ip
      }

      await serviceModel.addService(service).then(row => {
        res.json({
          code: 200,
          message: '提交成功！'
        })
      }).catch(err => {
        res.json({
          code: 10000,
          message: '提交失败！请稍后重试。'
        })
      })
    } else {
      res.json({
        code: 10001,
        message: '验证码错误，请重新输入！'
      })
    }
  } else {
    res.json({
      code: 10000,
      message: 'unknow'
    })
  }
}

pagesControl.getTeamList = async (req, res) => {
  const type = req.query.type || 1
  await teamModel.getTeamList(type).then(rows => {
    res.json({
      code: 200,
      message: '',
      detail: rows
    })
  }).catch(err => {
    res.json({
      code: 10001,
      message: '',
      detail: err
    })
  })
}

pagesControl.getBannerList = async (req, res) => {
  await bannerModel.getIndexBanner().then(rows => {
    res.json({
      code: 200,
      message: '',
      detail: rows
    })
  }).catch(err => {
    res.json({
      code: 10001,
      message: '',
      detail: err
    })
  })
}

module.exports = pagesControl
